package com.waypolice.manager.controller;

import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.manager.service.StudyManageService;
import com.waypolice.pojo.CmsStudymanages;
import com.waypolice.pojo.CmsStudymanagesExample;
import com.waypolice.pojo.UpmsUser;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 档案编研控制层
 * @autor lzh
 * @date 2019/3/25
 */
@Controller
@RequestMapping("/manage/studymanage")
public class UpmsStudyManagesController {
    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;
    @Autowired
    private StudyManageService studyManageService;

    @RequestMapping("/index")
    public String studyIndex(){
        return "/manage/studyManage/index";
    }

    /**
     * 已发布的档案编研记录
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public Object getList(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                          @RequestParam(required = false, defaultValue = "10", value = "limit") int limit){
        CmsStudymanagesExample example = new CmsStudymanagesExample();
        CmsStudymanagesExample.Criteria criteria = example.createCriteria();
        //未删除
        criteria.andStuSignDeleteEqualTo("0");
        //已发表
        criteria.andStuSignEqualTo("1");
        List<CmsStudymanages> cmsStudymanages = studyManageService.selectByExampleForOffsetPage(example,offset,limit);
        int total = studyManageService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", cmsStudymanages);
        result.put("total", total);
        return result;
    }

    @RequestMapping("/personal")
    public String infoPerosnal(){
        return "/manage/studyManage/myPersonal";
    }

    /**
     * 当前账号的档案编研记录
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping("/personalList")
    @ResponseBody
    public Object getPersonalList(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                                  @RequestParam(required = false, defaultValue = "10", value = "limit") int limit){

        Subject subject=SecurityUtils.getSubject();
        UpmsUser user = (UpmsUser)subject.getSession().getAttribute("loginUser");
        String userName = user.getUsername();
        CmsStudymanagesExample example = new CmsStudymanagesExample();
        CmsStudymanagesExample.Criteria criteria = example.createCriteria();
        //未删除
        criteria.andStuSignDeleteEqualTo("0");
        //提交人账号
        criteria.andStuOneEqualTo(userName);
        example.setOrderByClause("STU_UPDATE_DATE");
        List<CmsStudymanages> cmsStudymanages = studyManageService.selectByExampleForOffsetPage(example, offset, limit);
        Integer total = studyManageService.countByExample(example);
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",cmsStudymanages);
        return map;

    }

    /**
     * 跳转新增页面
     */
    @RequestMapping(value = "/create",method = RequestMethod.GET)
    public String createInfo(){
        return "/manage/studyManage/create";
    }
    /**
     * 新增业务
     */
    @RequestMapping(value = "/createAvtive")
    @ResponseBody
    public Object create(@RequestParam(value = "fileName" ,required = false)MultipartFile file,
                         HttpServletRequest request){

            String subject = request.getParameter("subject");
            if(StringUtils.isBlank(subject)){
                return new CmsResult(0,"主题不能为空",null);
            }
            String stumitter = request.getParameter("stumitter");
            if(StringUtils.isBlank(stumitter)){
                return new CmsResult(0,"提交人不能为空",null);
            }
            CmsStudymanages studymanages= new CmsStudymanages();
            studymanages.setSubject(subject);
            studymanages.setSubmitter(stumitter);
            String imgUrl = "";
        if ( file.getSize() != 0 ){

            try {
                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                String originalFilename = file.getOriginalFilename();
                String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String s = fastDFSClient.uploadFile(file.getBytes(),substring);
                imgUrl = IMAGE_SERVER_URL + s;
                studymanages.setStuFileAddress(imgUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        String uuid = UUID.randomUUID().toString();
        studymanages.setStuId(uuid);
        studymanages.setStuCreateDate(new Date());
        //未发表
        studymanages.setStuSign("0");
        //未删除
        studymanages.setStuSignDelete("0");
        request.getUserPrincipal();
        Subject security = SecurityUtils.getSubject();
        UpmsUser user = (UpmsUser)security.getSession().getAttribute("loginUser");
        //提交人账号
        studymanages.setStuOne(user.getUsername());
        int insert = studyManageService.insert(studymanages);
        if (insert >0){
            return new CmsResult(1,"添加成功",null);
        }else{
            return new CmsResult(0,"出现未知错误，添加失败",null);
        }
    }
    /**
     * 跳转编辑
     */
    @RequestMapping(value = "/update",method = RequestMethod.GET)
    public String updateInfo(String id, Model model){
        Map<String, Object> stringObjectMap = model.asMap();
        CmsStudymanages cmsStudymanages1 = studyManageService.selectByPrimaryKey(id);
        stringObjectMap.put("oneStudy",cmsStudymanages1);
        return "/manage/studyManage/update";
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@RequestParam(value = "fileName" ,required = false)MultipartFile file,HttpServletRequest request){
        String stuId = request.getParameter("stuId");
        if (StringUtils.isBlank(stuId)){
            return new CmsResult(0,"页面失效，请关闭重试",null);
        }
        String subject = request.getParameter("subject");
        if(StringUtils.isBlank(subject)){
            return new CmsResult(0,"主题不能为空",null);
        }
        String stumitter = request.getParameter("stumitter");
        if(StringUtils.isBlank(stumitter)){
            return new CmsResult(0,"提交人不能为空",null);
        }
        CmsStudymanages studymanages= studyManageService.selectByPrimaryKey(stuId);
        studymanages.setSubject(subject);
        studymanages.setSubmitter(stumitter);
        String imgUrl = "";
        if (file.getSize() != 0){
            try {

                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                String originalFilename = file.getOriginalFilename();
                String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String s = fastDFSClient.uploadFile(file.getBytes(),substring);
                imgUrl = IMAGE_SERVER_URL + s;
                studymanages.setStuFileAddress(imgUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        studymanages.setStuUpdateDate(new Date());
        int i = studyManageService.updateByPrimaryKey(studymanages);
        if (i>0){
            return new CmsResult(1,"修改成功",null);
        }else{
            return new CmsResult(0,"修改失败,请重试",null);
        }
    }

    /**
     * 删除自己的未发表的编研记录
     * @param request
     * @return
     */
    @RequestMapping("/myDelete")
    @ResponseBody
    public Object deleteMyArchive(HttpServletRequest request){
        String stuId = request.getParameter("stuId");
        if (stuId == null || "".equals(stuId)){
            return new CmsResult(0,"请求发生错误，请重新发送请求",null);
        }
        CmsStudymanages cmsStudymanages = studyManageService.selectByPrimaryKey(stuId);
        if (StringUtils.isNotBlank(cmsStudymanages.getStuFileAddress())){
            try {
                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                fastDFSClient.deleteFile(cmsStudymanages.getStuFileAddress());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int i = studyManageService.deleteByPrimaryKey(stuId);
        if (i==1){
            return new CmsResult(1,"删除成功",null);
        }
        return new CmsResult(0,"删除失败，请重试",null);
    }

    /**
     * 删除已发表的编研记录
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object deleteAnything(String id){
        CmsStudymanages cmsStudymanages = studyManageService.selectByPrimaryKey(id);
        cmsStudymanages.setStuUpdateDate(new Date());
        cmsStudymanages.setStuSignDelete("1");
        int i = studyManageService.updateByPrimaryKey(cmsStudymanages);
        if (i == 1){
            return new CmsResult(1,"删除成功",null);
        }else{
            return new CmsResult(0,"删除失败",null);
        }
    }

    @RequestMapping("/send")
    @ResponseBody
    public Object send(String stuId){
        CmsStudymanages cmsStudymanages = studyManageService.selectByPrimaryKey(stuId);
        cmsStudymanages.setStuUpdateDate(new Date());
        cmsStudymanages.setStuSign("1");
        int i = studyManageService.updateByPrimaryKey(cmsStudymanages);
        if (i == 1){
            return new CmsResult(1,"发表成功",null);
        }else{
            return new CmsResult(0,"发表失败",null);
        }
    }
}